package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.Blog;
import model.BlogDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/*
 * 通过这个类, 来实现一些后端提供的接口
 */
@WebServlet("/blog")
public class BlogServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 从 query string 中查询一下看是否有 blogId. 如果有就认为是查询指定博客; 如果没有就是查询所有博客.
        BlogDao blogDao = new BlogDao();
        //尝试获取一下 queryString 中的blogId字段
        String blogId = req.getParameter("blogId");
        if (blogId == null) {
            //queryString 不存在，说明这次请求是获取博客列表
            List<Blog> blogs = blogDao.selectAll();
            String respString = objectMapper.writeValueAsString(blogs);
            resp.setContentType("application/json;charset=utf8");
            resp.getWriter().write(respString);
        } else {
            //queryString 存在，说明本次请求获取的是指定id的博客
            Blog blog = blogDao.selectOne(Integer.parseInt(blogId));
            if (blogId == null) {
                System.out.println("当前blogId = " + blogId + "对应的博客不存在！");
            }
            String respString = objectMapper.writeValueAsString(blog);
            resp.setContentType("application/json;charset=utf8");
            resp.getWriter().write(respString);
        }
    }/*所以就看这个blogId是否存在，如果是存在的，此时获取的就是根据id查询的博客，
    如果不存在，此时查询的就是博客列表（全部的博客）*/
}